package net.oschina.git.hikoyan.helloapi.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by yan on 16/11/29.
 */
@RestController
@Api(value = "preview-api", description = "预览文件")
@RequestMapping(value = "/preview")
public class PreviewController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/{filename:.+}", method = RequestMethod.GET)
    @ApiOperation(value = "预览文件", httpMethod = "GET", notes = "预览文件")
    public void pdf(@ApiParam(name = "filename", value = "pdf文件名") @PathVariable("filename") String filename,
                    @ApiParam(name = "response", value = "response") HttpServletResponse response) {
        File pdfFile = new File("/Users/yan/Desktop/openOffice/" + filename);

        if (pdfFile.exists()) {
            String extension = FilenameUtils.getExtension(filename);
//            OfficeDocumentConverter converter = OpenOfficeContext.getDocumentConverter();
//            DocumentFormat format = converter.getFormatRegistry().getFormatByExtension(extension);

            InputStream inputStream = null;
            try {
                String contentType = new MimetypesFileTypeMap().getContentType(pdfFile);
//                response.setContentType(format.getMediaType());
                response.setContentType(contentType);
                response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes(), "ISO-8859-1") + "." + extension);
                response.setContentLength((int) pdfFile.length());
                inputStream = new FileInputStream(pdfFile);
                IOUtils.copy(inputStream, response.getOutputStream());
            } catch (Exception e) {
                logger.error(getClass().getName(), e);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }

        }
    }

}
